package com.mzj.saas.mservice.task;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haixiaoke.saas.repository.pojo.Order;
import com.haixiaoke.saas.repository.pojo.OrderAmountItem;
import com.haixiaoke.saas.repository.pojo.OrderOperatingRecord;
import com.haixiaoke.saas.repository.pojo.OrderWechatRefundRecord;
import com.haixiaoke.saas.repository.service.IOrderAmountItemService;
import com.haixiaoke.saas.repository.service.IOrderOperatingRecordService;
import com.haixiaoke.saas.repository.service.IOrderService;
import com.haixiaoke.saas.repository.service.IOrderWechatRefundRecordService;
import com.haixiaoke.saas.repository.util.GsonUtil;
import com.mzj.saas.commons.DateUtils;
import jodd.typeconverter.Convert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author panda
 * @Date 2023/5/4
 **/
@Slf4j
@Service
public class WxRefundCallBackService {

    @Autowired
    private IOrderService iOrderService;
    @Autowired
    private IOrderOperatingRecordService iOrderOperatingRecordService;
    @Autowired
    private IOrderWechatRefundRecordService iOrderWechatRefundRecordService;
    @Autowired
    private IOrderAmountItemService iOrderAmountItemService;

    public void callBackOrder(Map<String, String> result) {
        if (result == null) {
            log.error("公寓小程序订单-退款-回调数据获取异常");
            return;
        }

        log.info("微信小程序退款---公寓回调解析的参数为：{}", GsonUtil.toJson(result));

        String outTradeNo = result.get("out_trade_no");
        String[] split = outTradeNo.split("_");
        String refundStatus = result.get("refund_status");
        if (!"SUCCESS".equals(refundStatus)) {
            log.error("该订单微信退款业务失败，订单id为：{}", outTradeNo);
            return;
        }

        Order order = iOrderService.selectOrderStateById(split[0]);
        if (ObjectUtil.isEmpty(order)) {
            log.error("未找到公寓订单 out_trade_no：{}", split[0]);
            return;
        }

//        Integer totalAmount = Integer.parseInt((result.get("total_fee")));                    //订单总金额
        Integer refundFee = Integer.parseInt((result.get("refund_fee")));                     //退款金额
        // 单位： 分
        //todo 金额校验暂时注释
        Integer pAmount = Convert.toInteger(NumberUtil.mul(order.getPriceAmounts().doubleValue(), 100));
        /*if (refundFee.intValue() != pAmount) {
            log.error("公寓订单的计算金额和微信支付金额不匹配 orderId={},totalAmount={},cost={}",
                    outTradeNo, totalAmount, order.getPriceAmounts());
            return;
        }*/

        //添加订单退款回调接口
        OrderWechatRefundRecord refundRecord = OrderWechatRefundRecord.builder().outTradeNo(result.get("out_trade_no"))
                .transactionId(result.get("transaction_id"))
                .outRefundNo(result.get("out_refund_no"))
                .refundId(result.get("refund_id"))
                .totalFee(Double.valueOf(result.get("total_fee")))
                .settlementTotalFee(Double.valueOf(result.get("settlement_total_fee")))
                .refundFee(Double.valueOf(result.get("refund_fee")))
                .settlementRefundFee(Double.valueOf(result.get("settlement_refund_fee")))
                .refundStatus(refundStatus)
                .successTime(DateUtils.convert(result.get("success_time"), DateUtils.FORMAT_14))
                .successTimeStr(result.get("success_time"))
                .refundRecvAccout(result.get("refund_recv_accout"))
                .refundAccount(result.get("refund_account"))
                .refundRequestSource(result.get("refund_request_source"))
                .cashRefundFee(Integer.valueOf(result.get("cash_refund_fee"))).build();
        iOrderWechatRefundRecordService.insertOrderWechatRefundRecord(refundRecord);
        if (Order.ORDER_STATE_UN_REFUND.equals(order.getOrderState())) {
            DateTime nowTime = DateUtil.date();
            if (ObjectUtil.isEmpty(order.getRealityCheckOutTime())) {
                order.setOrderState(Order.ORDER_STATE_REFUND);
            } else {
                order.setOrderState(Order.ORDER_STATE_COMPLETION);
            }
            order.setUpdateTime(nowTime);
            order.setUpdateBy(OrderOperatingRecord.OPERATING_BY);
            int i = iOrderService.updateOrderState(order);
            if (i != 0) {
                //插入订单状态变更记录
                OrderOperatingRecord record = new OrderOperatingRecord();
                record.setOrderId(outTradeNo);
                record.setOrderSourceState(Order.ORDER_STATE_UN_REFUND);
                record.setOrderState(order.getOrderState());
                record.setRemark(OrderOperatingRecord.RECORD_REMARK_REFUNDED);
                record.setOperatingTime(nowTime);
                record.setOperatingBy(OrderOperatingRecord.OPERATING_BY);
                iOrderOperatingRecordService.insertOrderOperatingRecord(record);

                OrderAmountItem item = new OrderAmountItem();
                item.setRefundType(OrderAmountItem.GOODS_REFUND_YES);
                item.setUpdateTime(nowTime);
                item.setUpdateBy("System");
                item.setOrderId(outTradeNo);
                //修改收费项是否退款标识
                iOrderAmountItemService.updateOrderAmountItemByOrderId(item);
            } else {
                log.info("小程序退款回调--公寓订单状态修改失败，resultInt：{}，Order：{}", i, order);
            }
        }
    }
}
